<template>
  <div>
    <div>
      <el-form
        :model="Form"
        :rules="dataRule"
        ref="dataForm"
        label-width="80px"
      >
        <el-row>
          <el-col :span="8" v-if="!disable">
            <el-form-item label="选择邮箱:" prop="options">
              <el-select
                v-model="Form.eamilId"
                filterable
                allow-create
                default-first-option
                placeholder="请选择标签邮箱"
              >
                <el-option
                  v-for="item in optionseamil"
                  :key="item.id"
                  :label="item.type"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="收件人:" prop="options">
              <el-select
                v-model="Form.userId"
                filterable
                allow-create
                multiple
                default-first-option
                placeholder="请选择标收件人"
                style="width: 100%"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.email"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="主题" prop="theme">
              <el-input
                v-model="Form.theme"
                placeholder="请输入主题"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="邮件模版" prop="template">
          <el-select
            v-model="Form.template"
            placeholder="请选择邮件模版"
            @change="changeTemplateText"
          >
            <el-option
              v-for="(item, index) in templates"
              :key="index"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <p v-if="back">
          <el-row>
            <el-col :span="24">
              <el-form-item
                :key="index"
                :label="'替换' + item + ''"
                v-for="(item, index) in codeStr"
                :prop="item"
                label-width="100px"
              >
                <el-input
                  type="text"
                  v-model="dataForm[item]"
                  :placeholder="'请输入替换模版中${' + item + '}的内容'"
                  @input="replace(item)"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="模版显示 :" v-if="!this.Templatedisplay">
            <span>{{ templateText1 }}</span>
          </el-form-item>
        </p>
        <el-form-item
          label="正文"
          prop="content"
          style="height: 500px"
          v-if="this.Templatedisplay"
        >
          <vue-ueditor-wrap
            v-model="Form.content"
            :config="myConfig"
          ></vue-ueditor-wrap>
        </el-form-item>

        <div class="footer">
          <el-button type="primary" @click="getback()" v-if="back">返回</el-button>
          <el-button type="primary" @click="dataFormSubmit()">发送</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import VueUeditorWrap from "vue-ueditor-wrap";
export default {
  name: "clone",
  display: "Clone",
  order: 2,
  components: {
    draggable,
    VueUeditorWrap,
  },

  data() {
    return {
      Templatedisplay: true,
      myConfig: {
        // 如果需要上传功能,找后端小伙伴要服务器接口地址
        // serverUrl: this.$config.baseUrl + 'ueditor/ueditorConfig',
        serverUrl: "http://localhost:8080/wds-demo-web-api/ueditor",
        // 你的UEditor资源存放的路径,相对于打包后的index.html
        UEDITOR_HOME_URL: "/static/ueditor/",
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 工具栏是否可以浮动
        autoFloatEnabled: false,
        // 关闭自动保存
        enableAutoSave: true,
        toolbars: [
          [
            "undo", //撤销
            "bold", //加粗
            "indent", //首行缩进
            "italic", //斜体
            "underline", //下划线
            "strikethrough", //删除线
            "subscript", //下标
            "fontborder", //字符边框
            "superscript", //上标
            "formatmatch", //格式刷
            "fontfamily", //字体
            "fontsize", //字号
            "justifyleft", //居左对齐
            "justifycenter", //居中对齐
            "justifyright", //居右对齐
            "justifyjustify", //两端对齐
            "insertorderedlist", //有序列表
            "insertunorderedlist", //无序列表
            "lineheight", //行间距
          ],
        ],
        fontfamily: [
          { label: "", name: "songti", val: "宋体,SimSun" },
          { label: "仿宋", name: "fangsong", val: "仿宋,FangSong" },
          {
            label: "仿宋_GB2312",
            name: "fangsong",
            val: "仿宋_GB2312,FangSong",
          },
          { label: "", name: "kaiti", val: "楷体,楷体_GB2312, SimKai" },
          { label: "", name: "yahei", val: "微软雅黑,Microsoft YaHei" },
          { label: "", name: "heiti", val: "黑体, SimHei" },
          { label: "", name: "lishu", val: "隶书, SimLi" },
          { label: "", name: "andaleMono", val: "andale mono" },
          { label: "", name: "arial", val: "arial, helvetica,sans-serif" },
          { label: "", name: "arialBlack", val: "arial black,avant garde" },
          { label: "", name: "comicSansMs", val: "comic sans ms" },
          { label: "", name: "impact", val: "impact,chicago" },
          { label: "", name: "timesNewRoman", val: "times new roman" },
        ],
        // 初始容器高度
        initialFrameHeight: 350,
        // 初始容器宽度
        initialFrameWidth: "100%",
        // 上传文件接口
        enableAutoSave: false,
        elementPathEnable: false,
        wordCount: false,
      },
      param: {},
      codeStr: [],
      templateText: "",
      templateText1: "",
      options: [],
      optionseamil: [],
      visible: false,
      back: true, //返回设置状态
      sendMessage: {
        smsgMessageTemplate: {},
        contacts: [],
        content: "",
      },
      dataForm: {
        text: "",
        code: "",
      },
      Form: {
        id: 0,
        userId: "",
        theme: "",
        content: "",
        template: "",
      },
      textarea: "",
      templates: [],
      value: "",
      disable: true,
      dataRule: {
        theme: [{ required: true, message: "主题不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getgroup();
    this.emsgsetup();
    this.getTemplateList();
  },

  methods: {
    //获取邮箱配置
    emsgsetup() {
      this.$http({
        url: this.$http.adornUrl("/emsgsetup/emsgsetuplist"),
        method: "get",
        params: this.$http.adornParams({}),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.optionseamil = data.list;
          var id = data.list[0].id;
          this.Form.eamilId = this.optionseamil[0].id;
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    getback() {
      this.back = false;
      this.Templatedisplay = true;
      this.Form.template = "";
    },
    //获取用户
    getgroup() {
      this.$http({
        url: this.$http.adornUrl("/emsgcontact/getlist"),
        method: "get",
        params: this.$http.adornParams({}),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.options = data.list;
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    //选择模板
    changeTemplateText(value) {
      this.back = true;
      this.Templatedisplay = false;
      for (var i = 0; i < this.templates.length; i++) {
        var template = this.templates[i];
        if (value === template.id) {
          this.templateText = template.content;
          this.sendMessage.smsgMessageTemplate = template;
          /* 去除&nbsp; */
          let content = this.templateText.replace(/&nbsp;/gi, "");
          /* 去除空格 */
          let content1 = content.replace(/\s/gi, "");
          let content2 = content1.replace(/<.+?>/g, "");
          this.templateText1 = content2;
          this.codeStr = [];
        }
      }
      var str = this.sendMessage.smsgMessageTemplate.replaceCode;
      /* 去除&nbsp; */
      let content = this.sendMessage.smsgMessageTemplate.content.replace(
        /&nbsp;/gi,
        ""
      );
      /* 去除空格 */
      let content1 = content.replace(/\s/gi, "");
      let content2 = content1.replace(/<.+?>/g, "");
      var index = content2.indexOf("${");
      if (index != -1) {
        this.codeStr = this.getCode(content);
        // 动态添加校验
        for (let i = 0; i < this.codeStr.length; i++) {
          console.log(this.codeStr[i] + "xxxxxxxx");
          // this.dataRule[this.codeStr[i]] = [
          //   {
          //     required: true,
          //     message: "请输入替换模版中${" + this.codeStr[i] + "}的值",
          //     trigger: "blur",
          //   },
          // ];
        }
        var template1 = this.Form.template;

        this.dataForm = {};
        this.Form.template = template1;
      }
      this.param = {};
    },
    //取出内容中的占位符
    getCode(str) {
      var reg = /\$\{(.+?)\}/g;
      var list = [];
      var result = null;
      do {
        result = reg.exec(str);
        result && list.push(result[1]);
      } while (result);
      return list;
    },
    //替换模板中的内容
    replace(value) {
      if (this.templateText != "") {
        //替换模版中的${value}
        var text = this.templateText.format(this.dataForm);
        let content = text.replace(/&nbsp;/gi, "");
        /* 去除空格 */
        let content1 = content.replace(/\s/gi, "");
        let content2 = content1.replace(/<.+?>/g, "");
        this.templateText1 = content2;
      }
    },
    //获取用户
    getTemplateList() {
      this.$http({
        url: this.$http.adornUrl("/emsgemailtemplate/templatelist"),
        method: "get",
        params: this.$http.adornParams({}),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.templates = data.list;
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    //发送邮件
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/emsgsendmail/sendmail"),
            method: "post",
            data: this.$http.adornParams({
              email: this.Form.userId,
              subject: this.Form.theme,
              id: this.Form.eamilId,
              templateId: this.Form.template,
              param: this.dataForm,
              content: this.Form.content,
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "发送成功",
                type: "success",
                duration: 1500,
              });
            } else {
              this.$message.error();
            }
          });
        }
      });
    },
  },
};
String.prototype.format = function () {
  if (arguments.length == 0) return this;
  var obj = arguments[0];
  var s = this;
  for (var key in obj) {
    s = s.replace(new RegExp("\\${" + key + "\\}", "g"), obj[key]);
  }
  return s;
};
</script>
<style>
.list-group {
  display: flex;
  flex-direction: column;
  padding-left: 0;
  margin-bottom: 0;
  border: 0;
}
.list-group2 {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  padding-left: 0;
  margin-bottom: 0;
  border: 0;
}

.list-group-item:first-child {
  border-top-left-radius: 0.25rem;
  border-top-right-radius: 0.25rem;
}

.list-group-item {
  position: relative;
  display: block;
  padding: 0.75rem 1.25rem;
  margin-bottom: -1px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
  box-sizing: border-box;
}
.list-group-item2 {
  position: relative;
  display: inline-block;
  padding: 0.75rem 1.25rem;
  margin-bottom: -1px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
  box-sizing: border-box;
  width: 50%;
  pointer-events: none;
}

.el-collapse-item__header {
  border: 0;
}

.list-group-item {
  cursor: move;
}

h3 {
  font-size: 28px;
  margin-bottom: 20px;
}

.el-icon-circle-close {
  color: #c9a2a2;
  font-size: 20px;
  position: absolute;
  right: 30px;
  pointer-events: auto;
  line-height: 50px;
}

.el-icon-circle-close:hover {
  color: #f40;
}
.el-icon-arrow-right:before {
  dislpay: none !important;
  content: none;
  position: absolute;
  z-index: -999;
}
.el-collapse-item__arrow::before {
  dislpay: none !important;
}
.footer {
  margin-left: 45%;
}
</style>

